package com.mzj.saas.contract;

import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.entity.BacklogItemHouseUser;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.entity.UserDepartmentRef;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.department.repository.UserDepartmentRefRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.vo.HouseVO;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.entity.MatchUserHouse;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.property.repository.MatchUserHouseRepository;
import com.mzj.saas.mservice.sys.entity.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 实现房产合同期限剩余30天推送消息给对应的企业用户
 */
@Component
public class houseDeadline {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private UserDepartmentRefRepository userDepartmentRefRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private MatchUserHouseRepository matchUserHouseRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Scheduled(cron = "0 0 0 */1 * * ")
    public void contractDeadline() {

        String sql = "SELECT\n" +
                "\tb.id,\n" +
                "\tb.mobile AS phone \n" +
                "FROM\n" +
                "\tsaas_backlog_item_message_user a\n" +
                "\tLEFT JOIN saas_user b ON b.id = a.user_id \n" +
                "\tLEFT JOIN saas_department_hierarchy dh ON dh.org_id = a.org_id\n" +
                "WHERE a.type = 3";
        String houseSql = "SELECT\n" +
                "\t* \n" +
                "FROM\n" +
                "\t`saas_house` \n" +
                "WHERE\n" +
                "\t`status` = 1 \n" +
                "\tAND ( org_id = ? OR house_property_id = ? OR unit_lessee_id = ? )" ;
        List<AppUser> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(AppUser.class));
        for (AppUser user : query) {
            String userId = user.getId();
            List<UserDepartmentRef> byUserId = userDepartmentRefRepository.findByUserId(userId);
            if (!byUserId.isEmpty()) {
                Long depId = byUserId.get(0).getDepId();
                Optional<Department> byId = departmentRepository.findById(depId);
                if (byId != null) {
                    Long id = byId.get().getId();
                    List<House> houseList = jdbcTemplate.query(houseSql, new BeanPropertyRowMapper<>(House.class),id,id,id);
                    for (House house : houseList) {
                        String houseId = house.getId();
                        List<MatchUserHouse> byHouseId = matchUserHouseRepository.findByHouseId(houseId);
                        if (!byHouseId.isEmpty()) {
                            Date endDate = byHouseId.get(0).getEndDate();
                            Date date = new Date();
                            long time = endDate.getTime();
                            long datetime = date.getTime();
                            long num = time - datetime;
                            num = num/24/60/60/1000;
                            //剩余30天的时候推送消息
                            if (num == 30) {
                                String result = " SELECT sc.name AS residenceCommunityName,scb.name AS buildingNumName,scbu.name AS unitName,sh.room_number AS roomnumber";
                                String SQL = " FROM saas_house sh\n" +
                                        "        LEFT JOIN saas_community sc\n" +
                                        "        ON sh.residence_community_id = sc.id\n" +
                                        "        LEFT JOIN saas_community_build scb\n" +
                                        "        ON sh.building_num = scb.id\n" +
                                        "        LEFT JOIN saas_community_build_unit scbu\n" +
                                        "        ON sh.unit = scbu.id\n" +
                                        "        WHERE sh.id = ? ";
                                HouseVO houseVO = jdbcTemplate.queryForObject(result + SQL, new BeanPropertyRowMapper<>(HouseVO.class), houseId);
                                BacklogItem backlogItem = new BacklogItem();
                                backlogItem.setHouseId(houseId);
                                //backlogItem.setOrgId(house.getHouseNature() != null && house.getHouseNature() == 1?house.getOrgId():house.getHousePropertyId());
                                backlogItem.setType(50);
                                backlogItem.setTitle("房产合同还剩30天到期");
                                backlogItem.setContent(houseVO.getResidenceCommunityName()+houseVO.getBuildingNumName()+"栋"+houseVO.getUnitName()+"单元"+houseVO.getRoomNumber()+"号");
                                backlogItem.setBusinessStatus("待查看");
                                backlogItem.setHandleStatus(0);//0未读/未处理
                                backlogItem.setMatchUserId(user.getId());//承租人
                                backlogItem.setPhone(user.getPhone());//承租人
                                backlogItem.setCreateTime(new Date());
                                backlogItemRepository.save(backlogItem);
                            }
                            //剩余10天的时候推送消息
                            if (num == 10) {
                                String result = " SELECT sc.name AS residenceCommunityName,scb.name AS buildingNumName,scbu.name AS unitName,sh.room_number AS roomnumber";
                                String SQL = " FROM saas_house sh\n" +
                                        "        LEFT JOIN saas_community sc\n" +
                                        "        ON sh.residence_community_id = sc.id\n" +
                                        "        LEFT JOIN saas_community_build scb\n" +
                                        "        ON sh.building_num = scb.id\n" +
                                        "        LEFT JOIN saas_community_build_unit scbu\n" +
                                        "        ON sh.unit = scbu.id\n" +
                                        "        WHERE sh.id = ? ";
                                HouseVO houseVO = jdbcTemplate.queryForObject(result + SQL, new BeanPropertyRowMapper<>(HouseVO.class), houseId);
                                BacklogItem backlogItem = new BacklogItem();
                                backlogItem.setHouseId(houseId);
                                //backlogItem.setOrgId(house.getHouseNature() != null && house.getHouseNature() == 1?house.getOrgId():house.getHousePropertyId());
                                backlogItem.setType(50);
                                backlogItem.setTitle("房产合同还剩10天到期");
                                backlogItem.setContent(houseVO.getResidenceCommunityName()+houseVO.getBuildingNumName()+"栋"+houseVO.getUnitName()+"单元"+houseVO.getRoomNumber()+"号");
                                backlogItem.setBusinessStatus("待查看");
                                backlogItem.setHandleStatus(0);//0未读/未处理
                                backlogItem.setMatchUserId(user.getId());//承租人
                                backlogItem.setPhone(user.getPhone());//承租人
                                backlogItem.setCreateTime(new Date());
                                backlogItemRepository.save(backlogItem);
                            }
                        }
                    }
                }
            }

        }
    }
}